package com.issac.wxsearchcourse.controller;

import com.issac.wxsearchcourse.config.CheckUtil;
import com.issac.wxsearchcourse.config.MessageUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lmh
 * @date 2021/7/9 10:28
 **/

@RestController
public class searchController {
    //解析数据
    @PostMapping("/verify_wx_token")
    public String handler(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        Map<String, String> parseXml = MessageUtil.parseXml(request);
        String msgType = parseXml.get("MsgType");
        String content = parseXml.get("Content");
        String fromusername = parseXml.get("FromUserName");
        String tousername = parseXml.get("ToUserName");
        String MsgId = parseXml.get("MsgId");
        /*
        * 处理入参 数据交互响应给vx公众号
        *
        * */
        return "入参解析成功："+"MsgId:"+MsgId+"msgType"+msgType+"content:"+content+"fromusername:"+fromusername+"tousername:"+tousername;
    }


    //校验参数
    @GetMapping("/verify_wx_token")
    public void login(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            if (CheckUtil.checkSignature(signature, timestamp, nonce)) {
                out.write(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }
    }

}
